import { useState, useEffect, SetStateAction, useRef } from "react";
import {
  Table,
  Space,
  Button,
  Modal,
  Drawer,
  Form,
  Input,
  message,
} from "antd";
import instance from "../../axios/index";
import "./doctor.scss";

function Shop() {
  const [form] = Form.useForm();
  // 存储医生数据的状态
  const [doctorData, setDoctorData] = useState([]);
  // 存储总记录数的状态
  const [num, setNum] = useState(0);
  // 当前页码状态
  const [page, setPage] = useState(1);
  // 每页显示数量状态
  const [size, setSize] = useState(5);
  // 弹出框标题
  const [title, setTitle] = useState("");
  // 弹出框状态
  const [open, setOpen] = useState(false);
  // 图片地址
  const [img, setImg] = useState("");
  //点击编辑时当前行数据
  const [currentRecord, setCurrentRecord] = useState(null);
  // 绑定input输入框
  const refValue = useRef(null);
  // 点击删除
  const handleDelete = (id: unknown) => {
    Modal.confirm({
      title: "确认删除",
      content: "你确定要删除这位医生吗？",
      onOk: () => {
        instance.post("/api/doctordel", { id }).then((res) => {
          console.log(res.data.message);
        });
        // 删除成功后重新获取当前页的数据
        render();
      },
    });
  };
  // 封装分页函数
  function render() {
    const data = {
      page: page,
      size: size,
    };
    instance.post("/api/doctorall", data).then((res) => {
      if (res.data && res.data.data) {
        setNum(res.data.data.num);
        setDoctorData(res.data.data.data);
      } else {
        console.error("首次获取医生数据接口返回格式异常");
      }
    });
  }
  // 页面加载完成后获取数据
  useEffect(() => {
    render();
  }, []);
  //  点击分页
  const onChangePage = (
    page: SetStateAction<number>,
    pageSize: SetStateAction<number>
  ) => {
    // 更新当前页码和每页显示数量状态
    setPage(page);
    setSize(pageSize);
    // 调用封装分页的函数
    render();
  };

  // 定义表格列
  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    // 图片
    {
      title: "头像",
      dataIndex: "img",
      key: "img",
      render: (text: string | undefined) => (
        <img src={text} alt="" style={{ width: "50px", height: "50px" }} />
      ),
    },
    {
      title: "级别",
      dataIndex: "state",
      key: "state",
    },
    {
      title: "主科室",
      dataIndex: "department",
      key: "department",
    },
    {
      title: "学校",
      dataIndex: "nosocomium",
      key: "nosocomium",
    },
    {
      title: "主科室",
      dataIndex: "city",
      key: "city",
    },
    {
      title: "详细科室",
      dataIndex: "administrativeOffice",
      key: "administrativeOffice",
    },
    {
      title: "身份证",
      dataIndex: "identitycard",
      key: "identitycard",
    },
    {
      title: "操作",
      key: "operation",

      render: (_: unknown, record: { id: unknown }) => (
        <Space size="middle">
          <a onClick={() => updats_showModal(record)}>编辑</a>
          <Button type="link" danger onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // modal框
  const [isModalOpen, setIsModalOpen] = useState(false);
  //  点击新增按钮出现弹框
  const add_showModal = () => {
    setTitle("新增医生");
    setOpen(true);
    form.resetFields();
  };
  //  点击编辑按钮出现弹框
  const updats_showModal = (record) => {
    // 弹出框标题
    setTitle("编辑医生");
    // 数据回显
    form.setFieldsValue(record);
    // 存储当前行数据
    setCurrentRecord(record);
    // 弹出框打开
    setOpen(true);
    // 点击编辑拿到当条的数据
    console.log(record);
    // 回显图片
    setImg(record.img);
  };

  //  点击确认按钮关闭弹框
  const handleOk = () => {
    setIsModalOpen(false);
  };
  //  点击取消按钮关闭弹框
  const handleCancel = () => {
    setOpen(false);
  };
  //  点击确认
  const onFinish = () => {
    setOpen(false);
    if (title == "新增医生") {
      // 直接获取当前表单数据
      const data = form.getFieldsValue();
      const arr = {
        name: data.name,
        state: data.state,
        department: data.department,
        nosocomium: data.nosocomium,
        city: data.city,
        administrativeOffice: data.administrativeOffice,
        identitycard: data.identitycard,
        img: img,
      };
      //调用新增接口
      instance.post("/api/doctoradd", arr).then((res) => {
        if (res.data.code == 200) {
          message.success("新增成功");
        } else {
          message.error("新增失败");
        }
        render();
      });
      // 清空表单
      setImg("");
      form.resetFields();
    } else if (title == "编辑医生") {
      const data = form.getFieldsValue();
      const arr = {
        id: currentRecord.id,
        name: data.name,
        state: data.state,
        department: data.department,
        nosocomium: data.nosocomium,
        city: data.city,
        administrativeOffice: data.administrativeOffice,
        identitycard: data.identitycard,
        img: img,
      };
      // 调用编辑接口
      instance.post("/api/doctorupdate", arr).then((res) => {
        if (res.data.code == 200) {
          message.success("编辑成功");
        } else {
          message.error("编辑失败");
        }

        render();
      });
      // 清空表单
      setImg("");
      form.resetFields();
    }
  };
  // 点击取消
  const onFinishFailed = () => {
    setOpen(false);
  };
  // 点击上传更换头像到阿里云
  const filechange = (e) => {
    const file = e.target.files[0];
    if (file) {
      const formData = new FormData();
      formData.append("file", file);
      instance.post("/api/addimg", formData).then((res) => {
        setImg(res.data.url);
      });
    }
  };
  // 点击搜索
  const brnsearch = () => {
    if (refValue.current.value) {
      instance
        .post("/api/doctorfind", { name: refValue.current.value })
        .then((res) => {
          if (res.data.code == 200) {
            setDoctorData(res.data.data);
            setNum(res.data.num);
            setPage(1);
            setSize(5);
          } else {
            message.error("没有找到医生");
          }
        });
    }
  };
  // 点击X关闭
    const onClose = () => {
    setOpen(false);
  };

  return (
    <div>
      <header>
        <input
          ref={refValue}
          className="searchinp"
          type="text"
          placeholder="请输入搜索内容"
        />
        <button className="searchbtn" style={{ color: '#000' }} onClick={brnsearch}>
          搜索
        </button>
        <button className="addbtn" style={{ color: '#000' }} onClick={add_showModal}>
          增加
        </button>
      </header>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={doctorData}
        // 分页
        pagination={{
          pageSize: size,
          total: num,
          showTotal: (total) => `Total ${total} items`,
          onChange: onChangePage,
        }}
      />

      <Modal
        title={title}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okButtonProps={{ style: { display: "none" } }} // 隐藏确认按钮
        cancelButtonProps={{ style: { display: "none" } }} // 隐藏取消按钮
      ></Modal>

      <Drawer onClose={onClose} title={title} placement="right" open={open}>
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 15 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}

          autoComplete="off"
        >
          <Form.Item name="img">
            <input type="file" className="uploadinp" onChange={filechange} />
            <img className="img" src={img} alt="" />
          </Form.Item>
          <Form.Item
            label="名字"
            name="name"
            rules={[{ required: true, message: "请输入内容" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="级别"
            name="state"
            rules={[{ required: true, message: "请输入内容" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="主科室"
            name="department"
            rules={[{ required: true, message: "请输入内容" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="学校"
            name="nosocomium"
            rules={[{ required: true, message: "请输入内容" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="城市"
            name="city"
            rules={[{ required: true, message: "请输入内容" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="详细科室"
            name="administrativeOffice"
            rules={[{ required: true, message: "请输入内容" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="身份证"
            name="identitycard"
            rules={[{ required: true, message: "请输入内容" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item className="ok"  wrapperCol={{ offset: 0, span: 10 }}>
            <Button type="dashed" onClick={onFinish}>确认</Button>
            <Button type="dashed" className="emit1" onClick={()=>{setOpen(false)}}>取消</Button>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
}

export default Shop;
